'''
Author: LostPatrol_3
Date: 2023-11-04 18:39:49
LastEditors: LostPatrol_3
LastEditTime: 2023-11-04 18:39:53
Description: 
'''
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QVBoxLayout, QWidget

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 创建用户名标签和编辑框
        self.username_label = QLabel('Username')
        self.username_edit = QLineEdit(self)
        self.username_edit.setHidden(True)  # 初始时编辑框是隐藏的

        # 创建垂直布局管理器
        layout = QVBoxLayout()
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_edit)

        # 创建一个 QWidget 作为中央部件
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # 连接信号和槽
        self.username_label.mousePressEvent = self.toggleEditUsername
        self.username_edit.returnPressed.connect(self.saveUsername)

        self.setWindowTitle('Editable Username Example')
        self.setGeometry(200, 200, 400, 300)

    def toggleEditUsername(self, event):
        # 点击用户名标签时，切换为编辑模式
        self.username_label.setHidden(True)
        self.username_edit.setHidden(False)
        self.username_edit.setText(self.username_label.text())
        self.username_edit.setFocus()

    def saveUsername(self):
        # 编辑完成后，保存用户名到用户名标签中
        new_username = self.username_edit.text()
        self.username_label.setText(new_username)
        self.username_label.setHidden(False)
        self.username_edit.setHidden(True)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())
